<template>
  <div>
    <SearchContainer @search="getDataSource" @reset="() => formRef.resetFields()">
      <a-form ref="formRef" class="form-style-flex" :model="formState" :label-col="{ style: { width: '80px' } }">
        <a-form-item name="dhmc">
          <a-input v-model:value="formState.dhmc" class="w-64" placeholder="单号" />
        </a-form-item>
        <a-form-item name="dateRange" label="制单日期">
          <a-range-picker v-model:value="formState.dateRange" class="w-64" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item name="ckmc" label="盘点仓库" class="w-[350px]">
          <SelectWarehouse v-model:value="formState.ckmc" multiple :max-tag-count="2" @change="onSelectSupplier" />
        </a-form-item>
      </a-form>
    </SearchContainer>
    <a-card class="mt-2">
      <div class="flex">
        <a-button class="mb-2 mr-2" type="primary" @click="onClickEdit()"> 新增 </a-button>
        <!-- <a-button class="mb-2 ml-2"> 导出 </a-button> -->
        <BaseExport
          type="物资"
          name="盘点单"
          code="00001078"
          :search-params="{
            dhmc: formState.dhmc,
            ckid: formState.ckid,
            stdate: formState.dateRange?.[0],
            eddate: formState.dateRange?.[1]
          }"
          >导出</BaseExport
        >
      </div>
      <BaseTable
        :data-source="dataSource"
        class="expand-table"
        fill
        :expanded-row-keys="expandedRowKeys"
        :loading="loading"
        column-code="00001078"
        :pagination="{ total: page.total, current: page.current, pageSize: page.pageSize }"
        @change="onPageChange"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
          <!-- <template v-if="column.dataIndex === 'statusStr'">
            <span v-if="record.status === 0">新盘点</span>
            <span v-if="record.status === 1">盘点中</span>
            <span v-if="record.status === 2">待确认</span>
            <span v-if="record.status === 3">已确认</span>
            <span v-if="record.status === 4">已作废</span>
          </template> -->
          <template v-if="column.dataIndex === 'lsh'">
            <PopoverTable :config="detailConfig" :params="{ lsh: record.lsh, cxlx: 1 }" :width="1000">
              <template #bodyCell="{ column: popColumn, record: popRecord }">
                <template v-if="popColumn.dataIndex === 'mc'">
                  <MedicineInfo :value="{ mc: popRecord.mc, gg: popRecord.gg, cj: popRecord.cj }" />
                </template>
                <template v-if="popColumn.dataIndex === 'diffSl'">
                  <div :class="popRecord.diffSl > 0 ? 'text-red-500' : 'text-blue-700'">{{ popRecord.diffSl }}</div>
                </template>
              </template>
              {{ record.lsh }}
            </PopoverTable>
          </template>
          <!-- <template v-if="column.dataIndex === 'zeroflag'">
            {{ record.zeroFlag === 1 ? '包含' : '不包含' }}
          </template> -->

          <template v-if="column.dataIndex === 'action'">
            <a-space>
              <a-button type="link" size="small" :disabled="record.status === 4 || record.status === 3" @click="onDetail(record, 1)">盘点</a-button>
              <a-button type="link" size="small" :disabled="record.status !== 2" @click="onClickConfirm(record, 3)">确认</a-button>
              <a-button type="link" size="small" :disabled="record.status === 0 || record.status === 1 || record.status === 4" @click="onPrintInventory(record)"
                >差异表</a-button
              >
              <TableMoreButton>
                <a-button type="link" size="small" :disabled="record.status !== 0" @click="onClickEdit(record)">修改</a-button>
                <BaseButton
                  confirm-text="确认作废？"
                  :disabled="record.status === 4 || record.status === 3"
                  type="text"
                  danger
                  size="small"
                  @click="onCancel(record)"
                  >作废</BaseButton
                >
                <a-button type="link" size="small" @click="onPrint(record)"> 打印 </a-button>
                <a-button type="link" size="small" @click="onExport(record)"> 导出 </a-button>
              </TableMoreButton>
            </a-space>
          </template>
        </template>
      </BaseTable>
    </a-card>
    <AddModal v-model:open="open" :row-data="rowData" @ok="getDataSource" />
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import SearchContainer from '@/components/SearchContainer'
import SelectWarehouse from '@/components/SelectWarehouse'
import { post, http } from '@/utils/request'
import BaseTable from '@/components/BaseTable'
// import useUserStore from '@/store/user'
import AddModal from './AddModal.vue'

const router = useRouter()
// const { empName } = useUserStore()
const rowData = ref(null)
const formRef = ref(null)
const detailColumns = ref([])
const dataSource = ref([])
const expandedRowKeys = ref([])
const open = ref(false)
const loading = ref(false)
const formState = ref({
  dateRange: [dayjs(new Date().setDate(new Date().getDate() - 10)).format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  ckmc: '',
  dhmc: '',
  ckid: []
})
const page = ref({
  total: 0,
  current: 1,
  pageSize: getSystemConfig('DFFAULT_PAGE_SHOW_COUNT') || 10
})
const onDetail = (record, status) => {
  if (record.status === 0) {
    onClickConfirm(record, status)
  }
  router.push({
    path: '/material/warehouse/inventory-detail',
    query: {
      lsh: record.lsh
    }
  })
}
const onCancel = async (record) => {
  const { code } = await post('/materials/psiform/deCancelCheck', record)
  if (code !== 0) return message.error('作废失败')
  message.success('成功')
  getDataSource()
}
const onClickConfirm = async (record, status) => {
  const { code } = await post('/materials/psiform/doUpdateCheckStatus', { ...record, status })
  if (code !== 0) return message.error('失败')
  getDataSource()
}
const detailConfig = ref({
  url: '/materials/psiform/getInventoryDetailList',
  columnCode: '000161',
  rowKey: 'id',
  formatResult: (data) => {
    return data.map((item, index) => ({
      ...item,
      xh: index + 1
    }))
  }
})
const onClickEdit = (record = {}) => {
  rowData.value = Object.assign({}, record)
  open.value = true
}

const getDataSource = async () => {
  loading.value = true
  const { data, code, total, msg } = await post('/materials/psiform/getInventoryHeadList', {
    dhmc: formState.value.dhmc,
    // ckmc: formState.value.ckmc,
    ckid: formState.value.ckid,
    pageNum: page.value.current,
    pageSize: page.value.pageSize,
    stdate: formState.value.dateRange?.[0],
    eddate: formState.value.dateRange?.[1]
  })
  loading.value = false
  if (code !== 0) return message.error(msg)
  dataSource.value = data
  page.value.total = total
}
const getDetailColumns = async () => {
  const { data } = await post('/common/util/getTableMappingCloumnList', {
    id: '00001048'
  })
  detailColumns.value = data
}

// 差异表
const onPrintInventory = async (row) => {
  const { code, msg, data } = await post('/materials/psiform/printMtrKcStoreCheckCyList', { lsh: row.lsh })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印

  // const { code } = await post('/materials/psiform/doInventoryEnd', {
  //   dh: record.pddh,
  //   qrr: empName
  // })
  // if (code === 0) {
  //   onPrintInvenTory(record)
  //   getDataSource()
  //   message.success('盘点成功')
  // }
}
const onPageChange = ({ current, pageSize }) => {
  page.value.current = current
  page.value.pageSize = pageSize
  getDataSource()
}

// 打印
const onPrint = async (row) => {
  const { code, msg, data } = await post('/materials/psiform/printMtrKcStoreCheckList', { lsh: row.lsh })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

// 导出
const onExport = (row) => {
  http
    .post(
      '/materials/export',
      {
        parameters: {
          lsh: row.lsh
        },
        tblcode: '001062'
      },
      { responseType: 'blob' }
    )
    .then((res) => {
      const href = URL.createObjectURL(res.data)
      const element = document.createElement('a')
      element.download = '盘点单' + '.xlsx'
      element.href = href
      element.click()
    })
    .catch(() => {
      message.error('导出失败，请稍后重试！')
    })
}

onMounted(() => {
  getDataSource()
  getDetailColumns()
})

const onSelectSupplier = (_, supplier) => {
  formState.value.ckid = supplier.map((item) => {
    return item.ckid
  })
}
</script>
<style lang="less" scoped>
.detail-table {
  :deep(.ant-table) {
    margin-inline: 0 !important;
    border: 1px solid var(--primary-color);
  }
}
.expand-table {
  :deep(.ant-table) {
    .ant-table-tbody tr td:first-child {
      text-align: center;
      button {
        float: none !important;
      }
    }
  }
}
</style>
